"""
Case Type   : cm_ctl
Case Name   : gs_guc修改所有节点的参数值event_triggers,设置失败不支持
Create At   : 2023/04/24
Owner       : opentestcase012
Description :
    1.在所有节点创建文件并写入内容,赋给文件执行权限;
    2.在主节点执行,修改所有节点的参数值;
Expect      :
    1.创建成功
    2.失败，ERROR: The name of parameter "event_triggers" is incorrect.
History     :
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class DefinedResource(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'----{os.path.basename(__file__)} start----')
        self.common = Common()
        self.constant = Constant()
        self.pri_user = Node('PrimaryDbUser')
        self.primary_sh = primary_sh
        self.file1 = os.path.join(macro.DB_MY_PATH, 'event_triggers.sh')

    def test_cm(self):
        text = '----step1:在所有节点创建文件并写入内容,赋给文件执行权限; expect:成功----'
        self.log.info(text)
        cmd = f"echo 'echo event_triggers_sh contents' > {self.file1};" \
            f"chmod +x {self.file1};"
        res = self.primary_sh.exec_gs_ssh(cmd)
        self.assertIn('Successfully execute command on all nodes', res,
                      "执行失败:" + text)

        text = '----step2:在主节点执行,修改所有节点的参数值; expect:修改失败----'
        self.log.info(text)
        exp = 'ERROR: The name of parameter "event_triggers" is incorrect. ' \
              'It is not in the CMAGENT parameter range'
        guc_res = self.primary_sh.execute_gsguc(
            'set -Z cmagent ', exp,
            f"event_triggers='{{{{\"on_start\":\"{self.file1}\"}}}}'")
        self.log.info(guc_res)
        self.assertEqual(guc_res, exp, "执行失败:" + text)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        text1 = '----step3:恢复参数值并执行reload生效; expect:成功----'
        self.log.info(text1)
        cmd = f"source {macro.DB_ENV_PATH};" \
            "cm_ctl set --param --agent -k event_triggers='{{}}';" \
            f"cm_ctl reload --param --agent"
        self.log.info(cmd)
        cm_ctl_res1 = self.common.get_sh_result(self.pri_user, cmd)

        text2 = '----删除sh文件; expect:成功----'
        self.log.info(text2)
        cm_ctl_res2 = self.primary_sh.exec_gs_ssh(f'rm -rf {self.file1}')

        self.assertEqual(2, cm_ctl_res1.count('success'),
                         "执行失败:" + cm_ctl_res1)
        self.assertIn('Successfully execute command on all nodes', cm_ctl_res2,
                      "执行失败:" + text2)
        self.log.info(f'----{os.path.basename(__file__)} finish----')
